﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TTS工具
{
    public partial class FrmTTS : Form
    {
        public FrmTTS()
        {
            InitializeComponent();
        }

        private void FrmTTS_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 文字转换mp3、wav格式音频
        /// </summary>
        /// <param name="path">保存路径</param>
        /// <param name="input">输入文本</param>
        /// <returns></returns>
        public static bool TextVonvertToMP3(string path, string input,string fileType)
        {
            input = input.Trim();
            if (!string.IsNullOrWhiteSpace(input))
            {
                using (SpeechSynthesizer reader = new SpeechSynthesizer())
                {

                    //reader.SetOutputToWaveFile(path + ".mp3");
                    reader.SetOutputToWaveFile(path + fileType);// ".wav");
                    reader.Speak(input);
                    //reader.Rate //设置语速
                    //reader.
                    reader.SetOutputToDefaultAudioDevice();
                    reader.Dispose();
                }
                return true;
            }
            return false;
        }

        private void btnSaveMav_Click(object sender, EventArgs e)
        {
            //TextVonvertToMP3(System.Environment.CurrentDirectory, tbFileName.Text.Trim());
            try {
                TextVonvertToMP3(System.Environment.CurrentDirectory + "\\" + tbFileName.Text.Trim(), 
                    tbText.Text.Trim(),".wav");
            } catch {
                MessageBox.Show("转换异常，电脑系统可能缺少与TTS相关的库!");
            }
            
        }

        private void btnSaveMp3_Click(object sender, EventArgs e)
        {
            try
            {
                TextVonvertToMP3(System.Environment.CurrentDirectory + "\\" + tbFileName.Text.Trim(),
                    tbText.Text.Trim(), ".mp3");
            }
            catch
            {
                MessageBox.Show("转换异常，电脑系统可能缺少与TTS相关的库!");
            }
        }
    }
}
